package com.huazai.lock;

/**
 * 线程间中通信
 * if 中放wait可以产生虚假唤醒 说以用while
 *
 * @author huazai
 * @date 2024/2/2
 */
public class ThreadDemo1 {
    public static void main(String[] args) {
        final Share share = new Share();
        new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    share.incr();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "aa").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    share.des();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "bb").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    share.incr();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "cc").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    share.des();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "dd").start();
    }
}

class Share {
    private int number = 0;

    public synchronized void incr() throws InterruptedException {
        while (number != 0) {
            wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName() + "  number = " + number);
        this.notifyAll();
    }

    public synchronized void des() throws InterruptedException {
        while (number == 0) {
            wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName() + "  number = " + number);
        this.notifyAll();
    }
}
